import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import { useStore } from '@/hooks';
import { Button, Dialog, Message } from '@alifd/next';
import TaskInfoDrawer from './components/TaskInfoDrawer';
import OrderInfoDrawer from './components/OrderInfoDrawer';
import SetPriceDrawer from './components/SetPriceDrawer';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import CancelTask from './components/CancelTask';
import AlterationDrawer from './components/AlterationDrawer';
import SendCarDrawer from './components/SendCarDrawer';
import CancelCarDialog from './components/CancelCarDialog';
import EditOrderDrawer from './components/EditOrderDrawer';

const tableId = uniqueId('tauTable');

function parseRegion(s) {
  if (!s?.length) return {};
  return { main: s[0]?.itemId, minor: s[1]?.id };
}

function ScTask() {
  const { scTaskStore: store } = useStore();
  const curRef = useRef();
  const [modal, setModal] = useState([]);

  useEffect(() => {
    (async () => {
      await store.getCompanies();
    })();
  }, []);

  const handleOnSearch = (params) => {
    const { orderDate, startStations: __, endStations: ___, ...searchArgs } = params?.values;
    const { startStations, endStations } = params?.valueObjects;
    const [from, to] = orderDate || [];
    const { main: startMainArea, minor: startMinorAreas } = parseRegion(startStations?.selectedPath || {});
    const { main: endMainArea, minor: endMinorAreas } = parseRegion(endStations?.selectedPath || {});
    store._mainArgs.search = {
      taskType: '1',
      from,
      to,
      startMainArea,
      startMinorAreas,
      endMainArea,
      endMinorAreas,
      ...searchArgs,
    };
  };

  const handleTableAction = (info, action) => {
    switch (action) {
      case 'viewTask':
        handleOpenTask(info);
        break;
      case 'viewOrder':
        handleOpenOrder(info);
        break;
      case 'edit':
        handleOpenEdit(info);
        break;
      case 'setPrice':
        handleOpenSetPrice(info);
        break;
      case 'done':
        handleDoneTask(info);
        break;
      case 'cancel':
        handleCancelTask(info);
        break;
      // 任务变更
      case 'alteration':
        handleAlteration(info);
        break;
      // 任务派车
      case 'manual':
        handleSendCar(info);
        break;
      // 取消派车
      case 'cancelSendCar':
        handleCancelCar(info);
        break;
      case 'editOrder':
        handleEditOrder(info);
        break;
      // 中港通港币账户
      case 'HKAccountTicket':
        handleHKAccountTicket(info);
        break;
      default:
        break;
    }
  };

  const handleOpenTask = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['viewTask']);
  };

  const handleOpenOrder = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['viewOrder']);
  };

  const handleOpenEdit = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['edit']);
  };

  const handleOpenSetPrice = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['setPrice']);
  };

  const handleAlteration = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['alteration']);
  };

  const handleSendCar = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['manual']);
  };

  const handleCancelCar = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['cancelSendCar']);
  };

  const handleEditOrder = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['editOrder']);
  };

  const handleHKAccountTicket = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['HKAccountTicket']);
  };

  const handleDoneTask = async (taskInfo) => {
    Dialog.confirm({
      content: t`确认要完成任务?`,
      onOk: async () => {
        try {
          const { id } = taskInfo;
          await store.changeTaskState(id, { state: 5, flag: true });
        } catch (error) {
          console.log(error);
        }
      },
    });
  };

  const handleCancelTask = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['cancel']);
  };

  // 变更数据提交
  const handleCancel = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { id } = curRef.current;
        const { remark } = result;
        await store.cancelSendCar({ taskId: id, remark });
        Message.success({ content: t`取消成功` });
      } catch (e) {
        Message.error({ content: t`取消失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(result);
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 价格设置提交
  const handleSetPrice = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.updatePrice(result);
        Message.success({ content: t`设置价格成功` });
      } catch (e) {
        Message.error({ content: t`设置价格失败!${e.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 变更数据提交
  const handleUpdateCompany = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const {
          arCarrierCompanyId, arCarrierCompanyName, arCarrierCompanyPrice,
          id, remark = '', ticketFlag, dispatchOrderRemarks = '',
        } = toJS(result);
        const params = {
          carrierCompany: arCarrierCompanyId,
          carrierCompanyName: arCarrierCompanyName,
        };
        _.assign(params, {
          taskId: id,
          carrierCompanyPrice: arCarrierCompanyPrice,
          remark,
          dispatchOrderRemarks,
          ticketFlag,
        });
        await store.alterationCompany(params);
        Message.success({ content: t`变更成功` });
      } catch (e) {
        Message.error({ content: t`变更失败: ${e?.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'startStations',
            type: 'sc-station',
            props: { placeholder: t`始发站点`, changeOnSelect: true, style: { minWidth: '160px' } },
          },
          {
            name: 'endStations',
            type: 'sc-station',
            props: { placeholder: t`结束站点`, changeOnSelect: true, style: { minWidth: '160px' } },
          },
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始日期`, t`结束日期`],
            },
          },
          {
            name: 'states',
            type: 'select',
            props: {
              placeholder: t`任务状态`,
              dataSource: toSelectDataSource(ENUMS.states),
              mode: 'multiple',
            },
          },
          {
            name: 'carrierCompany',
            type: 'select',
            props: {
              placeholder: t`承运公司`,
              dataSource: store.companies,
              style: { width: 160 },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store._mainArgs.pg.page}
          pageSize={store._mainArgs.pg.size}
          total={store._mainArgs.total}
          sort={store._mainArgs.tableSort}
          onFetch={(pg) => { store._mainArgs.pg = pg; }}
          loading={store._mainArgs.loading}
          dataSource={toJS(store._mainArgs.dataSource)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
            {
              title: t`任务编号`,
              width: 168,
              cell: (v, _, row) => {
                const errorTickets = row?.tickets?.filter((p) => p.operatingTicketCode);
                const currentStatus = row?.tickets?.filter((p) => (p.errorMsg && p.errorMsg !== '') || (p.operatingTicketCode));
                return (
                  <Button
                    key={row.id}
                    type="primary"
                    text
                    onClick={() => handleTableAction(row, 'viewTask')}
                  >
                    <>
                      <span>{`${row.id} / ${row?.tickets?.length}`}</span>
                      {currentStatus.length !== 0 &&
                        <>
                          <span style={{ margin: '0 3px' }}>{'/'}</span>
                          <span style={{ color: (errorTickets?.length === row?.tickets?.length) ? '' : 'red' }}>{`${errorTickets?.length}`}</span>
                        </>
                      }
                    </>
                  </Button>
                );
              },
            },
            column('stationGroup', { width: 140 }),
            column('carrierCompanyName', { width: 70 }),
            column('driverPlate', { width: 128 }),
            column('showPrice', { width: 120 }),
            column('state', { width: 56 }),
            column('departureTime', { width: 120 }),
          ].concat(global.isAdmin ? [
            {
              title: t`相关订单`,
              width: 185,
              cell: (v, _, row) => {
                const { orderIds = [], tickets = [] } = row;
                const result = orderIds.map((orderId) => {
                  const ticketsForOrder = tickets.filter((ticket) => ticket.orderId === orderId);
                  return {
                    orderId,
                    count: ticketsForOrder.length,
                  };
                });
                return (
                  <>
                    {result.map((p, idx) => (
                      <Button
                        key={`${p.orderId}-${idx}`}
                        type="primary"
                        text
                        onClick={() => {
                          const info = {
                            orderId: p.orderId,
                            taskInfo: row,
                          };
                          handleTableAction(info, 'viewOrder');
                        }}
                      >
                        {`${p.orderId} / ${p.count}`}
                      </Button>
                    ))}
                  </>
                );
              },
            }]
            : [])
            .concat([{
              title: t`操作`,
              width: 120,
              cell: (v, i, record) => {
                const { state, scOrder } = record;
                const { companies } = global.getEnvCfg() || {};
                const funcMenu = [
                  {
                    title: '编辑',
                    onClick: () => handleTableAction(record, 'edit'),
                  },
                  {
                    title: '价格设置',
                    onClick: () => handleTableAction(record, 'setPrice'),
                    show: global.isAdmin,
                  },
                  {
                    title: '编辑订单',
                    onClick: () => handleTableAction(record, 'editOrder'),
                    show: (state === '1' || state === '2') && global.isAdmin,
                  },
                  {
                    title: '派车',
                    onClick: () => handleTableAction(record, 'manual'),
                    show: state === '1',
                  },
                  {
                    title: '任务变更',
                    onClick: () => handleTableAction(record, 'alteration'),
                    show: (state === '1' || state === '2') && global.isAdmin,
                  },
                  {
                    title: '取消派车',
                    onClick: () => handleTableAction(record, 'cancelSendCar'),
                    show: state === '2',
                  },
                  {
                    title: '任务完成',
                    onClick: () => handleTableAction(record, 'done'),
                    show: state === '2',
                  },
                  // {
                  //   title: '取消任务',
                  //   onClick: () => handleTableAction(record, 'cancel'),
                  //   show: state === '1' || state === '2',
                  // },
                ];
                return (
                  <MoreFuncDropDown
                    dropdownItems={funcMenu}
                    maxShow={1}
                  />
                );
              },
            }])
          }
        />
      </div>
      <TaskInfoDrawer
        visible={modal[0] === 'viewTask' || modal[0] === 'edit'}
        task={curRef.current}
        modal={modal}
        handleUpdate={handleUpdate}
        onClose={() => {
          setModal([]);
        }}
      />
      <OrderInfoDrawer
        visible={modal[0] === 'viewOrder'}
        orderId={curRef.current?.orderId}
        task={curRef.current?.taskInfo}
        onClose={() => {
          setModal([]);
        }}
      />
      <SetPriceDrawer
        visible={modal[0] === 'setPrice'}
        task={curRef.current}
        onClose={() => {
          setModal([]);
        }}
        onSubmit={handleSetPrice}
      />
      <CancelTask
        visible={modal[0] === 'cancel'}
        task={curRef.current}
        onClose={() => {
          setModal([]);
        }}
        onSubmit={handleCancel}
      />
      <AlterationDrawer
        visible={modal[0] === 'alteration'}
        task={curRef.current}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        modal={modal}
        onCancel={() => setModal([])}
        onSubmit={handleUpdateCompany}
      />
      <SendCarDrawer
        visible={modal[0] === 'manual'}
        task={curRef.current}
        modal={modal}
        onClose={() => {
          setModal([]);
        }}
        onSubmit={handleSetPrice}
      />
      <CancelCarDialog
        visible={modal[0] === 'cancelSendCar'}
        task={curRef.current}
        modal={modal}
        onClose={() => {
          setModal([]);
        }}
      />
      <EditOrderDrawer
        visible={modal[0] === 'editOrder'}
        task={curRef.current}
        modal={modal}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        onCancel={() => setModal([])}
      />
    </TauPage>
  );
}

export default observer(ScTask);
